package common

import (
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
)

// Body 统一响应结构体
type Body struct {
	// 状态码
	Code int32 `json:"code"`
	// 消息
	Message string `json:"message"`
	// 数据
	Data interface{} `json:"data"`
}

type ApplicationError struct {
	// 错误代码
	ErrorCode int32
	// 错误信息
	ErrorMsg string
}

func (a ApplicationError) Error() string {
	return a.ErrorMsg
}

func (a ApplicationError) Code() int32 {
	return a.ErrorCode
}

func (a ApplicationError) Msg() string {
	return a.ErrorMsg
}

// Response 响应
func Response(w http.ResponseWriter, resp interface{}, err error) {
	var body Body
	if err != nil {
		if errors.Is(err, ApplicationError{}) {
			fmt.Printf("err:%s", err)
			applicationError := ApplicationError{}
			errors.As(err, &applicationError)
			body.Code = applicationError.Code()
			body.Message = applicationError.Msg()
			return
		}
		body.Code = -1
		body.Message = err.Error()
	} else {
		body.Code = 0
		body.Message = "OK"
		body.Data = resp
	}
	httpx.OkJson(w, body)
}
